//初始化语言
initLan(JSON.parse(sessionStorage['srcLan']),'#srcLanBox','#srcLangText');
initLan(JSON.parse(sessionStorage['destLan']),'#destLanBox','#destLangText');

//选择源语言，目的语言
$("#srcLanBox dd").click(function(){
    selectLan(this,'#srcLangText');
})
$("#destLanBox dd").click(function(){
    selectLan(this,'#destLangText');
})

//调换语言
$("#gt-swap").click(function(){
    var id=$('#destLangText').attr('data-id');
    var name=$('#destLangText').text();
    $('#destLangText').attr('data-id',$('#srcLangText').attr('data-id'));
    $('#destLangText').text($('#srcLangText').text());
    $('#srcLangText').attr('data-id',id);
    $('#srcLangText').text(name);
})
//翻译
$("#translate-btn").click(function(){
    var msg={
        'userId':sessionStorage['userId'],
        'srcLan':parseInt($('#srcLangText').attr('data-id')),
        'destLan':parseInt($('#destLangText').attr('data-id')),
        'text':$("#srcWords").val()
    }
    translate(msg);
    return false;
})
$("#srcWords").on('input propertychange', function () {
    if ($("#srcWords").val().length == 2000){
        $("#textareaInputNumber").css("color","red");
    } else {
        $("#textareaInputNumber").css("color","black");
    }

    $("#textareaInputNumber").html($("#srcWords").val().length);
});
function initLan(data,obj1,obj2){
    $(obj1).find('dl').html('');
    var i=0;
    for(var attr in data){
        if(i==0){
            $(obj2).attr('data-id',data[attr]);
            $(obj2).text(attr);
        }
        var row=Math.ceil((i+1)/4);//第几行
        var index=(i+1)%4-1;//第几列
        if(index==-1){
            index=3;
        }
        $(obj1).find('li').eq(index).find('dl').append('<dd id="'+data[attr]+'">'+attr+'</dd>');
        i++;
    }
}
function selectLan(obj1,obj2){
    $(obj2).attr('data-id',$(obj1).attr('id'));
    $(obj2).text($(obj1).text());
    $(obj1).closest('.popup-wrap').hide();
}


function translate(msg) {
    if(sessionStorage['token']) {
        $.ajax({
            url: URL_ip + "/mt",
            type: "post",
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(msg),
            beforeSend: function(request) {
                request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
            },
            error: function (error) {
                //失败原因
            },
            success: function (data) {
                console.log(data)
                if (data.code == 0) {
                    $("#destWords").val(data.dest);
                }
            }
        })
    } else {
        alert('请先登录!');
        showLogin(0);
    }
}
